package com.sh.sales.happysales.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.sh.polymedicine.happysale.net.entity.Region;
import com.sh.polymedicine.happysale.result.SimpleResult;
import com.sh.polymedicine.happysale.service.envelop.HappySaleManager;
import com.sh.sales.happysales.R;
import com.sh.sales.happysales.adapter.RegionAdapter;
import com.sh.sales.happysales.app.AppData;
import com.sh.sales.happysales.app.utils.LoginOutUtil;
import com.sh.sales.happysales.base.BaseActivity;
import com.sh.sales.happysales.service.LoginObsever;
import com.sh.sales.happysales.view.NewToast;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Subscriber;

/**
 * Created by zhouyucheng on 2017/9/18.
 */

public class RegionActivity extends BaseActivity implements LoginObsever {
    private static final String TAG = "RegionActivity";
    @BindView(R.id.set_back)
    ImageView setBack;
    @BindView(R.id.profect_next)
    TextView profectNext;
    @BindView(R.id.current_location)
    TextView currentLocation;
    @BindView(R.id.grid_locations)
    GridView gridLocations;

    private Subscriber<List<Region>> regionSubscriber;
    private RegionAdapter adapter;
    private ArrayList<Region> mRegions = new ArrayList<>();
    private Region region;
    private Subscriber<SimpleResult> newRegionSubscriber;
    private String userSign;
    private int refreshSignTag = -1;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_region);
        ButterKnife.bind(this);
        mAppManager.addActivity(this);
        adapter = new RegionAdapter(RegionActivity.this, mRegions);
        mLoginObserable.registerObserver(this);
        userSign = AppData.getInstence().getmUserToken().getUserSign();
        initData();
        initViews();
    }

    private void initData() {
        refreshSignTag = 1;
        if (regionSubscriber != null) {
            if (!regionSubscriber.isUnsubscribed()) {
                regionSubscriber.unsubscribe();
            }
        }
        regionSubscriber = new Subscriber<List<Region>>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                Log.i(TAG, "onError: "+e);
                if (HappySaleManager.DATA_FAIL.equals(e.getMessage())) {
                    String message = e.getCause().getCause().getMessage();
                    NewToast.makeText(RegionActivity.this, message);
                    int ret =Integer.valueOf( e.getCause().getMessage()) ;
                    if (ret>=100&&ret<200){
                        LoginOutUtil.logOut(RegionActivity.this);
                    }
                } else if (HappySaleManager.DATA_NULL.equals(e.getMessage())) {
                    NewToast.makeText(RegionActivity.this, e.getCause().getMessage());
                } else {
                    NewToast.makeText(RegionActivity.this, "获取区域列表失败，请检查网络");
                }
            }

            @Override
            public void onNext(List<Region> regions) {
                if (regions != null) {
                    if (regions.size() > 0) {
                        mRegions.clear();
                        mRegions.addAll(regions);
                        region = mRegions.get(0);
                        currentLocation.setText(region.getName());
                        adapter.setPosition(0);
                    } else {
                        Log.i(TAG, "onNext: " + "区域列表为空");
                    }
                }
            }
        };
        mHappySaleManager.getRegionList(userSign, regionSubscriber).subscribe(regionSubscriber);

    }

    private void initViews() {
        gridLocations.setAdapter(adapter);
        gridLocations.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                adapter.setPosition(i);
                region = mRegions.get(i);
                currentLocation.setText(region.getName());
            }
        });
    }

    private void setResult() {
        refreshSignTag = 2;
        if (newRegionSubscriber != null) {
            if (newRegionSubscriber.isUnsubscribed()) {
                newRegionSubscriber.unsubscribe();
            }
        }
        newRegionSubscriber = new Subscriber<SimpleResult>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                Log.i(TAG, "onError: " + e);
                if (HappySaleManager.DATA_FAIL.equals(e.getMessage())) {
                    String message = e.getCause().getCause().getMessage();
                    NewToast.makeText(RegionActivity.this, message);
                    int ret =Integer.valueOf( e.getCause().getMessage()) ;
                    if (ret>=100&&ret<200){
                        LoginOutUtil.logOut(RegionActivity.this);
                    }
                } else if (HappySaleManager.DATA_NULL.equals(e.getMessage())) {
                    NewToast.makeText(RegionActivity.this, e.getCause().getMessage());
                } else {
                    NewToast.makeText(RegionActivity.this, "个人信息提交失败，请检查网络");
                }
                finish();
            }

            @Override
            public void onNext(SimpleResult result) {
                Intent intent = new Intent();
                intent.putExtra("change01", region.getId() + "");
                intent.putExtra("change02", region.getName());
                AppData.getInstence().getmUserInfoResult().setRegion(region.getId()+"");
                AppData.getInstence().getmUserInfoResult().setRegionName(region.getName());
                RegionActivity.this.setResult(5, intent);
                mAppManager.finishActivity(RegionActivity.this);
            }
        };
        mHappySaleManager.changeRegion(region.getId() + "", userSign, newRegionSubscriber).subscribe(newRegionSubscriber);
    }

    @OnClick(R.id.set_back)
    public void onViewClicked() {
        setResult();
    }

    @Override
    public void refreshUserSign(int Position) {
        userSign = AppData.getInstence().getmUserToken().getUserSign();
        switch (refreshSignTag) {
            case 1:
                initData();
                break;
            case 2:
                setResult();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        mLoginObserable.unregisterObserver(this);
        super.onDestroy();
    }
}
